package net.plankton.mjpeg;

import java.io.IOException;
import java.io.InputStream;

import net.plankton.CamRestart.Restart;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;

public class MovieLoader extends Thread{

	int errorCount=0;
	
	String ip;
	String dir;
	int maxCount = 0;
	
	InputStream is;
	
	public MovieLoader(String ip, String dir) {
		this.ip = ip;
		this.dir = dir;
	}
	
	public MovieLoader(String ip, String dir,int maxCount) {
		this.ip = ip;
		this.dir = dir;
		this.maxCount=maxCount;
	}
	
	@Override
	public void run() {
		while (true) {
			HttpClient client = new HttpClient();
			GetMethod get = new GetMethod("http://"+ip+"/img/video.mjpeg");
			try {
				client.executeMethod(get);
				is =get.getResponseBodyAsStream();
				ReadCam provider = new ReadCam(is);
				AviGenerator w = new AviGenerator(provider,dir,maxCount);
				w.setZDim(50);
				w.writeImage();
			} catch (Exception e) {
				
				e.printStackTrace();
			} 
			try {
				try {
					errorCount++;
					if (errorCount>10) {
						new Restart().run();
						Thread.sleep(30000);
						System.exit(0);
					}
					is.close();
					get.releaseConnection();
					Thread.sleep(4000);
//					get.abort();
					
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				Thread.sleep(10);
			}
			catch (Exception e) {}
		}
	}
	
	public static void main(String[] args) {
		HttpClient client = new HttpClient();
		GetMethod get = new GetMethod("http://192.168.1.102/img/video.mjpeg");
		try {
			client.executeMethod(get);
			
			ReadCam provider = new ReadCam(get.getResponseBodyAsStream());
			AviGenerator w = new AviGenerator(provider,"/tmp/javaAvi");
			w.setZDim(1000);
			w.writeImage();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
}
